import Gm from "../../../database/models/gm"
import {PlayerModel} from "../../../database/models/player";

export const typeDefs = `
type Player{
  _id:String!
  name: String!
  wechatOpenId: String
  headImgUrl: String
  coin: Int!
  freeCoin: Int!
  gem: Int!
  point: Int!
  phone: String,
  inviteBy: GM
  shortId: Int
}
`

export const queryDefs = `
  players(page:Int!,limit:Int): [Player]!
  searchPlayerByName(name:String!): [Player]!
  searchPlayerByPhone(phone:String!): [Player]!
  searchPlayerByShortId(shortId: Int!): Player
  getPlayerById(_id:String!): Player
`

export const mutationDefs = `
  playerAddCoin(_id:String!,coin:Int!): Player
  playerAddFreeCoin(_id:String!,freeCoin:Int!): Player
  playerAddGem(_id:String!,gem:Int!): Player
  playerAddPoint(_id:String!,point:Int!): Player
`

export const resolvers = {
  Query: {
    async players(_, {page = 0, limit = 20}) {
      return PlayerModel.find().skip(limit * page).limit(limit)
    },

    async searchPlayerByName(_, {name}) {
      const reg = new RegExp(name, 'ig')
      return PlayerModel.find({name: reg})
    },

    async getPlayerById(_, {_id}) {
      return PlayerModel.findById(_id)
    },

    searchPlayerByPhone(_, {phone}) {
      const reg = new RegExp(`^${phone}`, 'ig')
      return PlayerModel.find({phone: reg})
    },

    searchPlayerByShortId: async (_, {shortId}) => {
      // const reg = new RegExp(`^${shortId.toString()}`, 'ig')
      const ps = await PlayerModel.findOne({shortId}).lean()
      return ps
    }
  },
  Mutation: {
    async playerAddCoin(_, {_id, coin}) {
      if (coin <= 0) {
        throw Error('COIN_SHOULD_GT_0')
      }
      const p = await PlayerModel.findById(_id)
      if (!p)
        throw Error('NO_SUCH_PLAYER')

      return PlayerModel.findByIdAndUpdate(_id, {$inc: {coin}}, {new: true})
    },
    async playerAddFreeCoin(_, {_id, freeCoin}) {
      if (freeCoin <= 0) {
        throw Error('COIN_SHOULD_GT_0')
      }
      const p = await PlayerModel.findById(_id)
      if (!p)
        throw Error('NO_SUCH_PLAYER')

      return PlayerModel.findByIdAndUpdate(_id, {$inc: {freeCoin}}, {new: true})
    },
    async playerAddGem(_, {_id, gem}) {
      if (gem <= 0) {
        throw Error('GEM_SHOULD_GT_0')
      }

      const p = await PlayerModel.findById(_id)
      if (!p)
        throw Error('NO_SUCH_PLAYER')

      return PlayerModel.findByIdAndUpdate(_id, {$inc: {gem}}, {new: true})
    },
    async playerAddPoint(_, {_id, point}) {
      if (point <= 0) {
        throw Error('GEM_SHOULD_GT_0')
      }

      const p = await PlayerModel.findById(_id)
      if (!p)
        throw Error('NO_SUCH_PLAYER')

      return PlayerModel.findByIdAndUpdate(_id, {$inc: {point}}, {new: true})
    }
  },
  Player: {
    async inviteBy({inviteBy}) {
      if (!inviteBy) {
        return null
      }
      const gm = await Gm.findById(inviteBy)
      return gm
    }
  }
}
